
package com.sheep.netty.cryptogram;

import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;


public class AES2 {
    private static final String KEY = "12sa56781f345g7=";
//	public static void main(String[] args) throws Exception {
//		String content = "root";
//		String encryptResult = encrypt(content);
//		String decryptResult = decrypt(encryptResult);
//		System.out.println("加密后：" + encryptResult);
//		System.out.println("解密后：" + decryptResult);
//	}
    /**
     * 解密
     */
    public static String decrypt(String data) throws Exception {
        byte[] content = parseHexStr2Byte(data);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        KeyGenerator kgen = KeyGenerator.getInstance("AES"); // KeyGenerator提供（对称）密钥生成器的功能。使用getInstance 类方法构造密钥生成器。
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(KEY.getBytes("UTF-8"));
        kgen.init(128,random);// 使用用户提供的随机源初始化此密钥生成器，使其具有确定的密钥大小。
        SecretKey secretKey = kgen.generateKey();
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(KEY.getBytes("UTF-8")));// 使用解密模式初始化 密钥
        byte[] decrypt = cipher.doFinal(content);
        return new String(decrypt, "UTF-8"); // 加密
    }
    /**
     * 加密
     */
    public static String encrypt(String content) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(KEY.getBytes("UTF-8"));
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(KEY.getBytes("UTF-8")));// 使用加密模式初始化 密钥
        byte[] encrypt = cipher.doFinal(content.getBytes("UTF-8")); // 按单部分操作加密或解密数据，或者结束一个多部分操作。
        return parseByte2HexStr(encrypt);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static void main(String[] args) {
        try {
            System.out.println(decrypt("4D843275031B09120039E1D694FBB629"));
        } catch (Exception e) {
            e.printStackTrace();
        };
    }
}